package handler;

import bean.User;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Login implements Controller {
    private UserService service;

    public void setService(UserService service) {
        this.service = service;
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        ModelAndView modelAndView = new ModelAndView("login");
        if (req.getMethod().equals("POST")) {
            String userName = req.getParameter("user-name");
            String password = req.getParameter("password");
            if (User.verifyUserName(userName) && User.verifyPassword(password)) {
                User user = new User(userName, password);
                if (service.verify(user) > 0) {
                    session.setAttribute("user-name", userName);
                    modelAndView.setViewName("redirect:/home");
                } else {
                    modelAndView.addObject("error", "用户名或密码错误");
                }
            } else {
                modelAndView.addObject("error", "用户名或密码的长度不符合规范");
            }
        }
        return modelAndView;
    }
}
